package com.lzhl.buildjar.ui.support;

import javax.swing.*;
import javax.swing.border.LineBorder;
import javax.swing.plaf.UIResource;
import javax.swing.text.JTextComponent;
import java.awt.*;

/**
 * @author 李柱良(@柱子的日月)
 * @date 2016/5/4
 */
public class FillBorder extends LineBorder implements UIResource {
    private static Color errorColor = Color.RED;

    public FillBorder() {
        super(new Color(171, 173, 179), 1);
    }

    public Insets getBorderInsets(Component c)       {
        return getBorderInsets(c, new Insets(0,0,0,0));
    }

    public Insets getBorderInsets(Component c, Insets insets)       {
        Insets margin = null;
        //
        // Ideally we'd have an interface defined for classes which
        // support margins (to avoid this hackery), but we've
        // decided against it for simplicity
        //
        if (c instanceof AbstractButton) {
            margin = ((AbstractButton)c).getMargin();
        } else if (c instanceof JToolBar) {
            margin = ((JToolBar)c).getMargin();
        } else if (c instanceof JTextComponent) {
            margin = ((JTextComponent)c).getMargin();
        }
        insets.top    = (margin != null? margin.top : 0)    + thickness;
        insets.left   = (margin != null? margin.left : 0)   + thickness;
        insets.bottom = (margin != null? margin.bottom : 0) + thickness;
        insets.right =  (margin != null? margin.right : 0)  + thickness;

        return insets;
    }

    public Color getLineColor(Component c) {
        Boolean hasError = (Boolean) ((JTextComponent)c).getClientProperty("hasError");
        if(hasError != null && hasError) {
            return errorColor;
        }
        return this.lineColor;
    }

    public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
        Color oldColor = g.getColor();
        int i;

        /// PENDING(klobad) How/should do we support Roundtangles?
        g.setColor(getLineColor(c));
        for(i = 0; i < thickness; i++)  {
            if(!roundedCorners)
                g.drawRect(x+i, y+i, width-i-i-1, height-i-i-1);
            else
                g.drawRoundRect(x+i, y+i, width-i-i-1, height-i-i-1, thickness, thickness);
        }
        g.setColor(oldColor);
    }
}